package com.erp.order.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.order.domain.bo.ErpCutOrderRecordBo;
import com.erp.order.domain.bo.ErpSellerOrderExtendBo;
import com.erp.order.domain.bo.ErpSellerOrderLogBo;
import com.erp.order.domain.bo.ErpSendOutGoodsBo;
import com.erp.order.domain.vo.ErpSellerOrderLogVo;
import com.erp.order.mapper.ErpSellerChildOrderExtendMapper;
import com.erp.order.service.IErpSellerOrderLogService;
import com.erp.order.service.IErpSendOutGoodsService;
import com.ruoyi.common.core.annotation.RepeatSubmit;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.enums.*;
import com.ruoyi.order.api.RemoteErpOrderLogService;
import com.ruoyi.order.api.domain.ErpSellerChildOrderExtend;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.erp.order.domain.vo.ErpSellerOrderSelVo;
import com.erp.order.param.QueryOrderParam;
import com.erp.order.service.IErpSellerOrderService;
import com.ruoyi.auto.api.RemoteAutoSellerStoreService;
import com.ruoyi.auto.api.domain.ErpAutoSellerStoreConfig;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.order.api.domain.ErpSellerOrderExtend;
import com.ruoyi.order.api.domain.OrderStatusParam;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.system.api.RemoteDictDataService;
import com.ruoyi.system.api.domain.SysDictData;
import com.ruoyi.wallet.api.RemoteWalletLogService;
import com.ruoyi.wallet.api.RemoteWalletService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.wallet.api.domain.ErpSellerStoreWalletLog;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 卖家订单
 *
 * @author erp
 * @date 2023-03-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/order/sellerOrder")
public class ErpSellerOrderController extends BaseController {
    private final IErpSellerOrderService iErpSellerOrderService;
    private final IErpSellerOrderLogService iErpSellerOrderLogService;
    private final IErpSendOutGoodsService sendOutGoodsService;
    private final RemoteSellerStoreService sellerStoreService;
    private final RemoteAutoSellerStoreService autoSellerStoreService;
    private final RemoteWalletLogService remoteWalletLogService;
    private final RemoteWalletService remoteWalletService;
    private final RemoteDictDataService remoteDictDataService;


    /**
     * 线下声明发货
     */
    @GetMapping("/sellerShipmentForOther")
    public R<Object> sellerShipmentForOther(Long orderId,Integer type) {
        return iErpSellerOrderService.sellerShipmentForOther(orderId,type);
    }

    /**
     * 组包店铺
     */
    @GetMapping("/getHandoverOrderStoreList")
    public R<Object> getHandoverOrderStoreList() {
        return iErpSellerOrderService.getHandoverOrderStoreList();
    }

    /**
     * 截单和异常订单 红点
     */
    @GetMapping("/cutAndErrorRedReminder")
    public R<Object> cutAndErrorRedReminder() {
        return iErpSellerOrderService.cutAndErrorRedReminder();
    }

    /**
     * 组合打包红点
     */
    @GetMapping("/redReminderForHandoverOrder")
    public R<Object> redReminderForHandoverOrder() {
        return iErpSellerOrderService.redReminderForHandoverOrder();
    }

    /**
     * 获得申报商品长宽高
     */
    @GetMapping("/getOrderSkuPackageInfo")
    public R<Object> getOrderSkuPackageInfo(@Param("orderId") Long orderId) {
        return iErpSellerOrderService.getOrderSkuPackageInfo(orderId);
    }

    /**
     * 提交截单申请
     */
    @PostMapping("/cutOrderApplication")
    @Transactional
    public R<String> cutOrderApplication(@RequestBody ErpCutOrderRecordBo bo) {
        Long orderId = Long.parseLong(bo.getOrderId());
        // 截单原因
        String remark = "";
        String cancelType = bo.getCancelType();
        if (cancelType.equals("OT")) { // 其他原因,加上备注
            remark = bo.getCancelRemark();
        }else {
            R<String> cutOrderType = remoteDictDataService.getDictLabel("erp_cut_order_type", cancelType, SecurityConstants.INNER);
            remark = JSONObject.toJSONString(cutOrderType.getData());
        }
        iErpSellerOrderLogService.createOrderLog(orderId, null, OrderLogType.CutOrderApplication,
                remark, OrderProcessFlag.CutOff.getInfo(), "501");
        iErpSellerOrderService.setInnerStatus(orderId, "501", OrderProcessFlag.CutOff.getInfo());// 变为待截单
        return R.ok();
    }

    /**
     * 截单成功,不仓储
     */
    @GetMapping("/cutOrderGoods")
    @Transactional
    @RepeatSubmit
    public R<Object> cutOrderGoods(Long orderId) {
        // 只需要退还采购款,增加日志
        ErpSellerStoreWalletLog walletLog = remoteWalletLogService.getWalletLogByOrderNumber(orderId.toString());
        if (walletLog == null) {
            return R.fail("数据异常，请联系技术查看");
        }
        BigDecimal totalAmount = walletLog.getMoney();
        Long sellerId = walletLog.getSellerId();
        remoteWalletService.updateWallet(FlowType.INCOME.getCode(), ExpenseType.PURCHASEREFUND.getCode(),
                PayType.XT.getCode(), totalAmount, sellerId, orderId.toString(), "");

        // 添加日志
        iErpSellerOrderLogService.createOrderLog(orderId, null, OrderLogType.CutOrderSuccess, null, OrderProcessFlag.CutOff.getInfo(), "502");

        iErpSellerOrderService.setInnerStatus(orderId, "502", OrderProcessFlag.CutOff.getInfo());

        return R.ok();
    }

    /**
     * 根据店铺cn码，获取最新一条的订单信息
     * @param storeUserName
     * @return
     */
    @GetMapping("/getNewestOrderByStoreUserName/{storeUserName}")
    public R<Object> getNewestOrderByStoreUserName(@PathVariable("storeUserName") String storeUserName){
        ErpSellerOrder erpSellerOrder = iErpSellerOrderService.getNewestOrderByStoreUserName(storeUserName);
        return R.ok(erpSellerOrder);
    }

    /**
     * 根据orderId查询卖家订单列表并关联查询卖家订单商品列表
     */
    @GetMapping("/getProductInfoByOrderId")
    public R<ErpSellerOrder> getProductInfoByOrderId(Long orderId) {
        if (orderId == null) {
            return R.fail("订单详情查看失败");
        }
        return R.ok(iErpSellerOrderService.queryOrderAndProduct(orderId));
    }

    /**
     * 运营选择自发货
     */
    @GetMapping("/chooseSelfShipments")
    public R<Object> chooseSelfShipments(String orderIds) {
        return iErpSellerOrderService.chooseSelfShipments(orderIds);
    }

    /**
     * 上传采购信息
     */
    @GetMapping("/uploadPurchaseInfo")
    public R<Object> uploadPurchaseInfo(
            Long childOrderId,
            String proof,
            String purchasePrice,
            String cnTrackingNo
    ) {
        return iErpSellerOrderService.uploadPurchaseInfo(childOrderId, proof, purchasePrice, cnTrackingNo);
    }

    /**
     * 回显采购信息
     */
    @GetMapping("/queryPurchaseInfo")
    public R<Object> queryPurchaseInfo(
            Long childOrderId
    ) {
        return iErpSellerOrderService.queryPurchaseInfo(childOrderId);
    }

    /**
     * 确认线下手动发货 将状态改为107
     */
    @PostMapping("/uploadSendInfo")
    public R<Object> uploadSendInfo(
            @RequestBody ErpSellerOrderExtend erpSellerOrderExtend
    ) {
        return iErpSellerOrderService.uploadSendInfo(erpSellerOrderExtend);
    }
    
    @PostMapping("/sellerShipmentForMyself")
    public R<Object> sellerShipmentForMyself(
            @RequestBody ErpSellerOrderExtend erpSellerOrderExtend
    ) {
        return iErpSellerOrderService.sellerShipmentForMyself(erpSellerOrderExtend);
    }


    /**
     * 查询待审核订单
     */
    @GetMapping("/getReview")
    public Map<String, String> getReview() {
        // 判断该用户有没有待审核的订单
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(1);
        pageQuery.setPageSize(1);
        QueryOrderParam param = new QueryOrderParam();
        List<String> list = new ArrayList<>();
        list.add("101");
        param.setStatusList(list);
        param.setType(0);
        TableDataInfo<ErpSellerOrderSelVo> orderList = iErpSellerOrderService.selectOrderListNew(pageQuery, param);
        Map<String, String> map = new HashMap<>();
        if (orderList == null || orderList.getTotal() == 0) {
            map.put("str", "0");
        } else {
            map.put("str", "1");
        }
        return map;
    }

    /**
     * 为订单选择线上物流订单
     */
    @GetMapping("/updateWarehouseCarrierService")
    public R<ErpSellerOrder> updateWarehouseCarrierService(Long orderId, String logisticsServiceId) {
//        if (orderId == null) {
//            return R.fail("参数为空");
//        }
//        // 拿到订单
//        ErpSellerOrder erpSellerOrder = iErpSellerOrderService.queryByOrderId(orderId);
//        if (erpSellerOrder == null) {
//            return R.fail("该订单不存在");
//        }
//        erpSellerOrder.setWarehouseCarrierService(logisticsServiceId);
//        iErpSellerOrderService.updateWarehouseCarrierService(erpSellerOrder);

        return R.ok(null ,"修改成功");
    }

    /**
     * 采购审核不通过
     */
    @PostMapping("/reviewFailed")
    public R<Object> reviewFailed(@RequestBody OrderStatusParam orderParam) {

        Long orderId = orderParam.getOrderId();
        BigDecimal totalAmount = BigDecimal.ZERO;
        ErpSellerStoreWalletLog walletLog = remoteWalletLogService.getWalletLogByOrderNumber(orderId.toString());
        Long sellerId = walletLog.getSellerId();
        totalAmount = walletLog.getMoney();
        R<Object> returnR = remoteWalletService.updateWallet(FlowType.INCOME.getCode(),
                ExpenseType.ORDERREFUND.getCode(), PayType.XT.getCode(), totalAmount, sellerId,
                orderId.toString(), "");
        if (returnR.getCode() == 200) {
            iErpSellerOrderLogService.createOrderLog(orderId, null, OrderLogType.SubmitOrderFail,
                    orderParam.getRemark(), OrderProcessFlag.Begin.getInfo(), "101");
            iErpSellerOrderService.setInnerStatus(orderId, "101", OrderProcessFlag.Begin.getInfo());
        } else {
            return returnR;
        }
        return R.ok();
    }

    /**
     * 修改订单状态
     */
    @GetMapping("/setInnerStatus")
    public Integer setInnerStatus(@RequestParam("orderId") Long orderId,@RequestParam("status") String status,@RequestParam("flag") String flag) {
        return iErpSellerOrderService.setInnerStatus(orderId, status, flag);
    }
    
    /**
     * 根据orderId查询订单
     */
    @GetMapping("/getInfoByOrderId/{orderId}")
    public ErpSellerOrder getInfoByOrderId(@PathVariable("orderId") Long orderId) {
        return iErpSellerOrderService.getInfoByOrderId(orderId);
    }
    
    /**
     * 0803版 采购订单列表 查询订单和子订单
     */
    @GetMapping("/selectOrderListNew")
    public TableDataInfo<ErpSellerOrderSelVo> selectOrderListNew(QueryOrderParam bo, PageQuery pageQuery) {
        bo.setType(1);
        return iErpSellerOrderService.selectOrderListNew(pageQuery, bo);
    }

    /**
     * 订单列表 查询订单和子订单
     */
    @GetMapping("/selectOrderListUser")
    public TableDataInfo<ErpSellerOrderSelVo> selectOrderListUser(QueryOrderParam bo, PageQuery pageQuery) {
        List<String> orderProcessFlag = bo.getOrderProcessFlag();
        List<String> list = new ArrayList<>();
        list.add("problem");
        list.add("invalid");
        list.add("cutoff");
        list.add("myself");
        list.add("evaluation");
        list.add("out");
        boolean b = true;
        for (String s : list) {
            if (orderProcessFlag == null || orderProcessFlag.contains(s)) {
                b = false;
                break;
            }
        }
        if (b) {
            orderProcessFlag.add("companyEva");
        }
        // 查询该用户所拥有的店铺
        ErpSellerStoreEmpower erpSellerStoreEmpower = new ErpSellerStoreEmpower();
        Long userId = SecurityUtils.getUserId();
        if (userId != 1)
            erpSellerStoreEmpower.setUserId(userId);
        R<Object> sellerStoreListByInfo = sellerStoreService.getSellerStoreListByInfo(erpSellerStoreEmpower);
        List<ErpSellerStoreEmpower> selectList = JSONArray.parseArray(JSONObject.toJSONString(sellerStoreListByInfo.getData()), ErpSellerStoreEmpower.class);
        List<String> storeUserNameList = selectList.stream().map(ErpSellerStoreEmpower::getStoreUserName)
                .collect(Collectors.toList());
        if (storeUserNameList.size() == 0)
            storeUserNameList.add("restrict");
        bo.setStoreUserNameList(storeUserNameList);
        return iErpSellerOrderService.selectOrderListNew(pageQuery, bo);
    }

    /**
     * 自动化订单列表
     */
    @GetMapping("/selectOrderAssociation")
    public TableDataInfo<ErpSellerOrderSelVo> selectOrderAssociation(QueryOrderParam bo, PageQuery pageQuery) {
        List<String> orderProcessFlag = bo.getOrderProcessFlag();
        List<String> list = new ArrayList<>();
        list.add("problem");
        list.add("invalid");
        list.add("cutoff");
        list.add("myself");
        list.add("evaluation");
        list.add("out");
        boolean b = true;
        for (String s : list) {
            if (orderProcessFlag == null || orderProcessFlag.contains(s)) {
                b = false;
                break;
            }
        }
        if (b) {
            orderProcessFlag.add("companyEva");
        }
        // 查询该用户所关联的店铺
        ErpSellerStoreEmpower erpSellerStoreEmpower = new ErpSellerStoreEmpower();
        Long userId = SecurityUtils.getUserId();
        if (userId != 1)
            erpSellerStoreEmpower.setUserId(userId);
        R<Object> sellerStoreListByInfo = autoSellerStoreService.selectAutoStore(userId, 1);
        List<ErpAutoSellerStoreConfig> storeConfigList = JSONArray.parseArray(JSONObject.toJSONString(sellerStoreListByInfo.getData()), ErpAutoSellerStoreConfig.class);
        List<String> storeUserNameList = storeConfigList.stream().map(ErpAutoSellerStoreConfig::getStoreAlias)
                .collect(Collectors.toList());
        if (storeUserNameList.size() == 0)
            storeUserNameList.add("restrict");
        bo.setStoreUserNameList(storeUserNameList);
        return iErpSellerOrderService.selectOrderListNew(pageQuery, bo);
    }


//
//
//    /**
//     * 标记发货列表
//     */
//    @GetMapping("/markShipment")
//    public TableDataInfo<ErpSellerOrder> markShipment(QueryOrderParam bo, PageQuery pageQuery) {
//        return iErpSellerOrderService.markShipment(bo, pageQuery);
//    }
//
//    /**
//     * 获取订单店铺层级关系
//     */
//    @GetMapping("/getErpAgentBranchInfo")
//    public R<Object> getErpAgentBranchInfo(Long orderId) {
//        return iErpSellerOrderService.getErpAgentBranchInfo(orderId);
//    }
//
//    /**
//     * 获取订单店铺层级关系
//     */
//    @GetMapping("/getErpAgentBranchInfoByStore")
//    public R<Object> getErpAgentBranchInfoByStore(String storeStr) {
//        return iErpSellerOrderService.getErpAgentBranchInfoByStore(storeStr);
//    }
//
//    /**
//     * 确认订单是否发货成功
//     */
//    @GetMapping("/confirmOrderShippedType")
//    public R<Object> confirmOrderShippedType(Long orderId, Integer type) {
//        return iErpSellerOrderService.confirmOrderShippedType(orderId, type);
//    }

    /**
     * 获取角标
     */
    @GetMapping("/getStatementOrder")
    public R<Map<String, Integer>> getStatementOrder(QueryOrderParam bo) {
        Integer statementOrder = iErpSellerOrderService.getStatementOrder(bo);
        Map<String, Integer> map = new HashMap<>();
        map.put("count", statementOrder);
        return R.ok(map);
    }

////    /**
////     * 查询订单列表
////     */
////    @SaCheckPermission("system:sellerOrder:list")
////    @GetMapping("/getOrderList")
////    public TableDataInfo<ErpSellerOrderVo> getOrderList(ErpSellerOrderBo bo, PageQuery page,Long userId) {
////        if (userId != null) {// 运营
////            List<ErpSellerStoreEmpower> storeInfo = getStoreInfo();
////            Set<String> collect = storeInfo.stream().map(ErpSellerStoreEmpower::getStoreUserName).collect(Collectors.toSet());
////            List<ErpSellerOrderVo> voTableDataInfo = iErpSellerOrderService.queryList(bo);
////            List<ErpSellerOrderVo> erpSellerOrderVoList = voTableDataInfo.stream().filter(tem -> collect.contains(tem.getSellerLoginId())).collect(Collectors.toList());
////            return TableDataInfo.build(erpSellerOrderVoList);
////        }
////        return iErpSellerOrderService.queryPageList(bo,page);
////    }



    /**
     * 批量修改订单erp内部状态
     *
     * @param param 订单参数
     * @return
     */
    @PostMapping("/alterInnerStatus")
    public R<Void> alterInnerStatus(@RequestBody OrderStatusParam param) {
        List<Long> orderIds = param.getOrderIds();
        for (Long orderId : orderIds) {

            iErpSellerOrderService.setInnerStatus(orderId, param.getErpInnerOrderStatus(), "begin");
            iErpSellerOrderLogService.createOrderLog(orderId, null, OrderLogType.AlterOrderToBegin,
                    "", OrderProcessFlag.Begin.getInfo(), "101");
        }
        return R.ok();
    }

    /**
     * 订单作废
     */
    @PostMapping("/cancelOrder")
    public R<Void> cancelOrder(@RequestBody OrderStatusParam param) {
        List<Long> orderIds = param.getOrderIds();

        for (Long orderId : orderIds) {
            // 添加日志
            iErpSellerOrderLogService.createOrderLog(orderId, null, OrderLogType.CancelOrder, null, OrderProcessFlag.Invalid.getInfo(), "901");
            iErpSellerOrderService.setInnerStatus(orderId, "901", OrderProcessFlag.Invalid.getInfo());
        }
        return R.ok();
    }

    /**
     * 上传凭证
     */
    @PostMapping(value = "/uploadProof")
    public R<Object> uploadProof(@RequestBody ErpSendOutGoodsBo bo) {
        return sendOutGoodsService.updateOrInsertProof(bo);
    }

//    /**
//     * 补充订单列表
//     */
//    @GetMapping("/getSupplementOrder")
//    public TableDataInfo<ErpSellerOrder> getSupplementOrder(PageQuery pageQuery, QueryOrderParam param) {
//        return iErpSellerOrderService.getSupplementOrder(pageQuery, param);
//    }
//
//    /**
//     * 补充购买信息
//     */
//    @PostMapping("/uploadPurchaseProof")
//    public R<Void> uploadPurchaseProof(@RequestBody List<ErpSendOutGoodsBo> bo) {
//        return toAjax(iErpSellerOrderService.uploadPurchaseProof(bo));
//    }
//
//    /**
//     * 补充物流信息
//     */
//    @PostMapping("/uploadLogisticsProof")
//    public R<Boolean> uploadLogisticsProof(@RequestBody ErpSellerOrderExtendBo bo) {
//
//        Integer disputeResult = bo.getDisputeResult();
//        if (disputeResult != null && disputeResult != 0) { // 不是无需退款,必须要填写退款金额
//            if (StringUtils.isEmpty(bo.getDisputeAmount()) && bo.getDisputeImg() == null) {
//                return R.fail("请填写纠纷信息");
//            }
//        }
//        if (disputeResult == null) {
//            // 判断是否填写采购凭证
//            List<ErpSellerChildOrderExtend> childOrderExtendList = childOrderExtendMapper.selectList(new LambdaQueryWrapper<ErpSellerChildOrderExtend>()
//                    .eq(ErpSellerChildOrderExtend::getOrderId, bo.getOrderId()));
//            if (childOrderExtendList.size() == 0) {
//                return R.fail("请先填写购买信息");
//            }
//            for (ErpSellerChildOrderExtend childOrderExtend : childOrderExtendList) {
//                if (childOrderExtend.getPurchasePrice() == null) {
//                    return R.fail("请先填写购买信息");
//                }
//            }
//        }
//        return R.ok(iErpSellerOrderService.uploadLogisticsProof(bo));
//    }

//    /**
//     * 查看物流凭证
//     */
//    @GetMapping("/getLogisticsProof")
//    public R<ErpSellerOrderExtend> getLogisticsProof(Long orderId) {
//        return R.ok(iErpSellerOrderService.getLogisticsProof(orderId));
//    }
//
//    @GetMapping("/getPurchaseProof")
//    public R<ErpSellerChildOrderExtend> getPurchaseProof(String childOrderId) {
//        return R.ok(iErpSellerOrderService.getPurchaseProof(childOrderId));
//    }
//
//    @GetMapping("/getPurchaseProofList")
//    public R<List<ErpSellerChildOrderExtend>> getPurchaseProofList(Long orderId) {
//        return R.ok(iErpSellerOrderService.getPurchaseProofList(orderId));
//    }

    /**
     * 查看驳回记录和截单记录
     *
     * @param log
     * @return
     */
    @PostMapping("/getRejectAndCutOffRecord")
    public TableDataInfo<ErpSellerOrderLogVo> getRejectAndCutOffRecord(@RequestBody ErpSellerOrderLogBo log, PageQuery pageQuery) {
        return iErpSellerOrderLogService.getRejectAndCutOffRecord(pageQuery, log);
    }


    /**
     * 设置订单备注
     */
    @GetMapping("/setOrderMemo")
    public R<Object> setOrderMemo(Long orderId,String memo) {
        return iErpSellerOrderLogService.setOrderMemo(Long.valueOf(orderId),memo);
    }

//    /**
//     * 获取订单详情
//     */
//    @GetMapping("/selectOrderDetails")
//    public R<Object> selectOrderDetails(QueryOrderParam bo) {
//        return iErpSellerOrderService.selectOrderDetails(bo);
//    }

}
